What we will cover
- Prerequisities and how to get started
- (R)Markdown 101
- Customising R markdown elements and outputs
- To interactivity and beyond!
Version 1.0 (08 August 2017)
What we will cover
For this workshop
Presenters: Maurits Evers, Sebastian Kurscheid
Slides: https://github.com/mevers/workshop_RMarkdown
What you should bring / have brought
What you should be familiar with
dataframe is; how to produce a plot; how to inspect an element, …Important R packages
pkg <- c("ggplot2", "rmarkdown", "knitr", "dplyr");
lapply(pkg, function(x) { if (!require(x, character.only = TRUE, quietly = TRUE)) {
install.packages(x);
require(x, quietly = TRUE)}
})
Example data
We will use the starwars dataset from dplyr.
head(starwars, n = 3);
## # A tibble: 3 x 13 ## name height mass hair_color skin_color eye_color birth_year ## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> ## 1 Luke Skywalker 172 77 blond fair blue 19 ## 2 C-3PO 167 75 <NA> gold yellow 112 ## 3 R2-D2 96 32 <NA> white, blue red 33 ## # ... with 6 more variables: gender <chr>, homeworld <chr>, species <chr>, ## # films <list>, vehicles <list>, starships <list>
Create new RMarkdown (Rmd) document in RStudio
Specify output option
Render
Document conversion
rmarkdown::render() (note that knitr::pandoc() is deprecated)rmarkdown::render() uses the universal document converter pandoc (installed as part of RStudio)
For example, pandoc will translate
# Header
into the following output-specific lines:
For HTML output
<h1>Header</h1>
For \(\LaTeX\) output
\section{Header}Beware the different Markdown flavours: GitHub, R Markdown, vanilla Markdown, …
Here: Focus on RMarkdown, and the following elements
More details:
Headers
# Header 1 ## Header 2 ### Header 3 #### Header 4
Emphasis
*italic*, _italic_ **bold**, __bold__
Lists
1. Level 1
+ Item 1
+ Item 2
2. Level 2
+ Item 3
+ Item 4
3. Level 3
Images and links
 [RStudio](https://www.rstudio.com/) [email@email.com](mailto:email@email.com)
Blockquote
> RStudio makes R easier to use. It includes a code editor, debugging & visualization tools.
Rules
----, ****
Manual line breaks
End line with two or more whitespaces.
Line 1 ends here,␣␣ line 2 start here.
Tables
Assemble list of words, and divide them with hyphens - (for the first row), and then separating each column with a pipe |.
First Header | Second Header ------------ | ------------- Cell 1 | Cell 2 Cell 3 | cell 4
Fenced code blocks
Lines wrapped within an environment with leading and tailing ``` are converted into a code block.
An optional language identifier provides syntax highlighting.
```bash echo "3 + 4" ```
R code blocks will be evaluated and printed (replace double with single curly brackets).
```{{r}}
3 + 4
```
Inline code
Use single backticks ` (delete curly brackets)
`{r} summary(starwars)`
Equations
The power of \(\LaTeX\) (MathJax)
$x = a$
$$ int_{x=0}^\infty dx \log{1+x} $$
You can use language-specific expressions in RMarkdown documents.
For example:
<img src="path/to/image.png" style="width:200px;"> to place an image,<hr> to place a horizontal rule,<ol start="10"><li>...</ol> to create an ordered list,\includegraphics[width=\textwidth]{...} to place an image,\begin{minipage}{.5\textwidth}...\end{minipage} to fine-tune horizontal and vertical text/figure layout,Beware: A HTML statement won't be recognised if you render your RMarkdown file as a Word document.
Growing list of output options
--- title: "Main title" subtitle: "Subtitle" author: "Firstname Lastname" date: "07/08/2017" output: word_document ---
Main keys
author)format(Sys.time(), '%d %B %Y'))html_document, pdf_document, word_document, ioslides_presentation, beamer_presentationSome useful options
eval=FALSE: Don't run code.include=FALSE: Run code but don't include the chunk in the output document.echo=FALSE: Don't show code, show results.results='hide': Show code, don't show results.message=FALSE: Don't show any additional R messages.error=FALSE: Don't show R error messages.warning=FALSE: Don't show R warning messages.cache=TRUE: Use cached results (if available) until the code chunk is changed.fig.width=7, fig.height=7: Set actual figure width and height to 7 inches.out.width=5, out.height=5: Set output document figure width and height to 5 inches; if fig.width, fig.height are different, the output is scaled.
More chunk options can be found e.g. in the R Markdown Reference Guide and in knitr's documentation.
Hint:
# R code # Extract all films per character df <- cbind.data.frame(film = unlist(starwars$films)); ggplot(data = df, aes(film)) + geom_bar();
Different ways to present tabular data.
Manual table creation
First Header | Second Header ------------ | ------------- Cell 1 | Cell 2 Cell 3 | cell 4
knitr::kable() (all output)
pander::pandoc.table() (all output)
xtable::xtable() (only HTML and \(\LaTeX\) output)
stargazer::stargazer() (only HTML and \(\LaTeX\) output)
DT::datatable() (only HTML output, interactive)
knitr::kable()# Load R package knitr and show table suppressMessages(library(knitr)); kable(starwars[1:6, 1:6])
| name | height | mass | hair_color | skin_color | eye_color |
|---|---|---|---|---|---|
| Luke Skywalker | 172 | 77 | blond | fair | blue |
| C-3PO | 167 | 75 | NA | gold | yellow |
| R2-D2 | 96 | 32 | NA | white, blue | red |
| Darth Vader | 202 | 136 | none | white | yellow |
| Leia Organa | 150 | 49 | brown | light | brown |
| Owen Lars | 178 | 120 | brown, grey | light | blue |
DT::datatable()# Load R package DT and show table suppressMessages(library(DT)); DT::datatable(starwars[, 1:10], options = list(pageLength = 6, scrollX = TRUE));
starwars in a Word document using a suitable R method.starwars in a HTML document using a suitable R method.
Note: Depending on the R method, you might have to install additional R packages, e.g. for pander:
# R code
# Install (if necessary) and load R package 'pander'
if (!require("pander", quietly = TRUE)) {
install.packages("pander");
require("pander", quietly = TRUE)}
ggplot2 from the tidyverseplotlyd3heatmpscatterD3networkD3streamgraphLoad the necessary libraries
suppressMessages(library(scatterD3));
plotly::ggplotly()suppressMessages(library(plotly));
## Warning: package 'plotly' was built under R version 3.4.1
ggplotly(ggplot(starwars, aes(x = height, y = mass, label = name)) + geom_point(), height = 3);
scatterD3::scatterD3()scatterD3(x = starwars$height, y = starwars$mass, lab = starwars$name);
R Markdown and shiny
…